<template>
  <div class="contact-management">
    <div class="container">
      <div class="header">
        <h1>联系人信息管理系统</h1>
        <div>
          <el-button type="primary" icon="Plus" @click="addContact">新增联系人</el-button>
          <el-button icon="Refresh" @click="refreshData">刷新</el-button>
        </div>
      </div>

      <div class="stats-bar">
        <div class="stat-item">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总联系人</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.primary }}</div>
          <div class="stat-label">主要联系人</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.active }}</div>
          <div class="stat-label">有效联系人</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.pending }}</div>
          <div class="stat-label">待更新</div>
        </div>
      </div>

      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchForm.keyword" placeholder="姓名/职位" clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.department" placeholder="部门" clearable>
              <el-option label="技术部" value="tech"></el-option>
              <el-option label="市场部" value="marketing"></el-option>
              <el-option label="销售部" value="sales"></el-option>
              <el-option label="人力资源" value="hr"></el-option>
              <el-option label="财务部" value="finance"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.ownerType" placeholder="所有者类型" clearable>
              <el-option label="企业" value="company"></el-option>
              <el-option label="个人" value="individual"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="searchContacts">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <div class="card-container">
        <!-- 联系人卡片 -->
        <div v-for="contact in contacts" :key="contact.id" class="contact-card">
          <div class="card-header">
            <h3>
              <el-icon><User /></el-icon>
              {{ contact.name }}
              <span v-if="contact.is_primary" class="primary-badge">主要联系人</span>
            </h3>
            <div>ID: {{ contact.id }}</div>
          </div>
          <div class="card-body">
            <div class="contact-info">
              <div class="info-row">
                <div class="info-label">所有者类型:</div>
                <div class="info-value">{{ contact.owner_type }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">所有者ID:</div>
                <div class="info-value">{{ contact.owner_id }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">职位:</div>
                <div class="info-value">{{ contact.position }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">部门:</div>
                <div class="info-value">{{ contact.department }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">备注:</div>
                <div class="info-value">{{ contact.remark }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">地址:</div>
                <div class="info-value">{{ contact.address }}</div>
              </div>
            </div>
            
            <div class="contact-methods">
              <div v-if="contact.mobile" class="contact-method">
                <div class="method-icon">
                  <el-icon><Iphone /></el-icon>
                </div>
                <div>{{ contact.mobile }}</div>
              </div>
              <div v-if="contact.phone" class="contact-method">
                <div class="method-icon">
                  <el-icon><Phone /></el-icon>
                </div>
                <div>{{ contact.phone }}</div>
              </div>
              <div v-if="contact.email" class="contact-method">
                <div class="method-icon">
                  <el-icon><Message /></el-icon>
                </div>
                <div>{{ contact.email }}</div>
              </div>
              <div v-if="contact.wechat" class="contact-method">
                <div class="method-icon">
                  <el-icon><ChatRound /></el-icon>
                </div>
                <div>{{ contact.wechat }}</div>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <div>创建时间: {{ formatDateTime(contact.create_time) }}</div>
            <div>更新时间: {{ formatDateTime(contact.update_time) }}</div>
          </div>
          <div class="action-buttons">
            <el-button type="primary" plain icon="Edit" @click="editContact(contact)">编辑</el-button>
            <el-button type="success" plain icon="Message" @click="sendMessage(contact)">发送消息</el-button>
            <el-button type="danger" plain icon="Delete" @click="deleteContact(contact)">删除</el-button>
          </div>
        </div>

        <!-- 空状态卡片 -->
        <div v-if="contacts.length === 0" class="empty-card">
          <el-icon :size="60" color="#C0C4CC"><Plus /></el-icon>
          <p>暂无联系人信息</p>
          <el-button type="primary" icon="Plus" style="margin-top: 20px;" @click="addContact">新增联系人</el-button>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container" v-if="contacts.length > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { 
  Search, Plus, User, Iphone, Phone, Message, ChatRound 
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router';
import { getContactInfo } from './supplier.js';

const router = useRouter();

// 统计数据
const stats = ref({
  total: 128,
  primary: 42,
  active: 86,
  pending: 12
})

// 搜索表单
const searchForm = ref({
  keyword: '',
  department: '',
  ownerType: ''
})

// 响应式数据
const contacts = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const totalRecords = ref(0);

// 获取联系人数据
const fetchContactData = async () => {
  try {
    loading.value = true;
    
    /*分页查询需要提供的参数*/
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    };
    
    /*调用联系人接口*/
    const response = await getContactInfo(queryParams);
    
    if (response.code === 200) {
      // 将后端数据映射到前端结构
      contacts.value = response.data.records.map(item => ({
        id: item.id,
        owner_type: item.ownerType,
        owner_id: item.ownerId,
        name: item.name,
        position: item.position,
        department: item.department,
        phone: item.phone,
        mobile: item.mobile,
        email: item.email,
        wechat: item.wechat,
        is_primary: item.isPrimary,
        address: item.address,
        remark: item.remark,
        create_time: item.createTime,
        update_time: item.updateTime
      }));
      
      totalRecords.value = response.data.total;
      // 更新统计数据（这里假设接口返回了统计数据）
      if (response.data.stats) {
        stats.value = response.data.stats;
      }
    } else {
      console.error('获取数据失败:', response.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  } finally {
    loading.value = false;
  }
};

// 日期时间格式化函数
const formatDateTime = (dateTimeString) => {
  return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
}

// 搜索联系人
const searchContacts = () => {
  currentPage.value = 1; // 重置到第一页
  fetchContactData();
}

// 刷新数据
const refreshData = () => {
  searchForm.value = {
    keyword: '',
    department: '',
    ownerType: ''
  };
  currentPage.value = 1;
  fetchContactData();
}

// 新增联系人
const addContact = () => {
  console.log('新增联系人')
}

// 编辑联系人
const editContact = (contact) => {
  console.log('编辑联系人:', contact)
}

// 发送消息
const sendMessage = (contact) => {
  console.log('发送消息给:', contact.name)
}

// 删除联系人
const deleteContact = (contact) => {
  console.log('删除联系人:', contact.name)
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchContactData();
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchContactData();
}

onMounted(() => {
  fetchContactData();
});

// 监听分页参数变化
watch([currentPage, pageSize], () => {
  fetchContactData();
});
</script>

<style scoped>
.contact-management {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: #f5f7fa;
  padding: 20px;
  color: #333;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.header h1 {
  font-size: 24px;
  color: #303133;
}
.stats-bar {
  display: flex;
  justify-content: space-between;
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.stat-item {
  text-align: center;
  padding: 0 15px;
}
.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409EFF;
}
.stat-label {
  font-size: 14px;
  color: #909399;
}
.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}
.contact-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.contact-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.card-header {
  background: linear-gradient(135deg, #409EFF 0%, #64b5ff 100%);
  padding: 15px 20px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}
.primary-badge {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}
.card-body {
  padding: 20px;
}
.contact-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.info-row {
  display: flex;
}
.info-label {
  width: 100px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}
.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
  line-height: 1.5;
}
.contact-methods {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}
.contact-method {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 13px;
}
.method-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}
.card-footer {
  padding: 15px 20px;
  background-color: #fafafa;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}
.empty-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  grid-column: 1 / -1;
}
.empty-card p {
  font-size: 16px;
  margin-bottom: 20px;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .stats-bar {
    flex-direction: column;
    gap: 15px;
  }
  .card-container {
    grid-template-columns: 1fr;
  }
}
</style>